package org.dataframework.security.core.db;

import java.sql.*;
import java.util.List;

/**
 * @Author: LiuCf
 * @Email: 1316640406@qq.com
 * @Date: 2021/7/3 13:06
 */
public class DefaultMysqlJdbcTemplate implements JdbcTemplate {
    public static final String DEF_URL = "jdbc:mysql://localhost:3306/data-security";
    public static final String DEF_USERNAME = "root";
    public static final String DEF_PASSWORD = "root";
    public static final String DEF_DRIVER = "com.mysql.cj.jdbc.Driver";

    private Connection connection;

    public DefaultMysqlJdbcTemplate() {
    }

    @Override
    public <T> T select(String sql, Class<T> clazz, RowMapper<T> rowMapper) throws SQLException {
        PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        List<T> rows = rowMapper.mapRow(resultSet);
        return rows.get(0);
    }

    @Override
    public <T> List<T> selectAll(String sql, Class<T> clazz, RowMapper<T> rowMapper) throws SQLException {
        PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        List<T> rows = rowMapper.mapRow(resultSet);
        return rows;
    }

    private Connection getConnection() throws SQLException {
        return DriverManager.getConnection(DefaultMysqlJdbcTemplate.DEF_URL, DefaultMysqlJdbcTemplate.DEF_USERNAME, DefaultMysqlJdbcTemplate.DEF_PASSWORD);
    }
}
